package com.atcc.test.serviceImpl;

import java.util.ArrayList;
import java.util.List;


import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.stereotype.Service;

import com.atcc.test.domain.User;
import com.atcc.test.service.UserService;

@Service
public class SecurityUserService<T extends User> implements UserDetailsService{
	private String userOldPassword = null;

	@Autowired
	private UserService userService;
	
	@Override
	public UserDetails loadUserByUsername(String userName) throws UsernameNotFoundException {
		try {
			User user = userService.findByUserName(userName);
			if(user == null) {
				throw new UsernameNotFoundException("用户名不存在");
			}
			userOldPassword = user.getPassword();
		    user.setPassword(new BCryptPasswordEncoder().encode(userOldPassword));
		    System.out.println(user.getPassword());
			List<SimpleGrantedAuthority> authorities = new ArrayList<>();
			if(StringUtils.isNotBlank(user.getRoles())) {
				String[] roles = user.getRoles().split(",");//split() 方法用于把一个字符串分割成字符串数组
				for(String role:roles) {
					if(StringUtils.isNotBlank(role))
						// String中的trim()方法的作用就是去掉字符串前面和后面的空格
						authorities.add(new SimpleGrantedAuthority(role.trim()));
				}
			}
			return new org.springframework.security.core.userdetails.User(user.getUserName(), user.getPassword(), authorities);
		}
		catch(Exception e){
			e.printStackTrace();
			return null;
		}
		
	}

}
